<template>
  <div>
    <el-form label-width="90px" label-position="left" ref="editForm">
      <el-form-item label="现场图:" prop="pic">
        <imgUploadModle @getChildValue="getChildValue" imgNumber="1" page="teachingPic"
                        :picSrc="editForm.pic"></imgUploadModle>
      </el-form-item>
      <el-row :span="24">
        <el-col :span="12">
          <el-form-item label="区角名称:" prop="name">
            <el-input v-model="editForm.name" auto-complete="off" placeholder="填写区角名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="区角位置:" prop="section_id">
            <component
              v-bind:is="item.propertyType"
              :property.sync="item"
              v-for="(item, index) in getPower"
              :key="index"
              @updateVal="updateVal"
            ></component>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="位置类型:" prop="position_id">
            <el-select v-model="editForm.position_id" placeholder="请选择位置类型" class="selectBox">
              <el-option
                v-for="item in positionList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开放时间:" prop="open_week">
            <el-select v-model="editForm.open_week" multiple placeholder="请选择" class="selectBox">
              <el-option
                v-for="item in weekTime"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="区角负责人:">
            <div style="display: flex">
              <span v-if="applyUserBox" class="mr-10">{{ applyUserBox ? applyUserBox.realname : '' }}</span>
              <el-button size="small" @click="cornerUserFn">选择区角负责人,默认位置负责人</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="区角类目:">
            <v-selectpage :data="cateList" key-field="id" show-field="name" class="form-control"
                          v-model="editForm.cate_id" placeholder="选择区角类目"
                          title="选择区角类目" style="width: 100%;" v-if="!editId"></v-selectpage>
            <span v-else @click="ruleVisible=true" class="showCateFn">{{ cateData ? cateData.name : '无' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="达标时长:" prop="time">
            <div style="display: flex">
              <el-input v-model="editForm.time" auto-complete="off" placeholder="达标时长" class="w-140"></el-input>
              <i class="edit-taps">分钟</i>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参与人数:">
            <el-input v-model="editForm.number" auto-complete="off" placeholder="可参与人数" class="w-140"></el-input>
            <i class="edit-taps">每天可参与预约人数</i>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="基本分值:">
            <el-input v-model="editForm.base_score" auto-complete="off" placeholder="" class="w-140"></el-input>
            <i class="edit-taps">生成后不可编辑</i>
          </el-form-item>
          <!--          <el-form-item label="基本分值:" v-else>-->
          <!--            {{ editForm.base_score }}-->
          <!--          </el-form-item>-->
        </el-col>
        <el-col :span="24">
          <el-form-item label="学习品质:">
            <el-select placeholder="请选择学习品质" v-model="study_ids" multiple style="width: 100%">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="item in selectList"
                :ksy="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
<!--        <el-col :span="24">-->
<!--          <el-form-item label="设置目标:" prop="description">-->
<!--            <el-input v-model="editForm.description" auto-complete="off" placeholder="设置目标" type="textarea"></el-input>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="24">
          <el-form-item label="场景:" prop="description">
            <el-button type="primary" @click="showCornerTheme" size="small">新增场景</el-button>
            <el-table
              ref="multipleTable"
              :data="editForm.themes"
              tooltip-effect="dark"
              style="width: 100%">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                label="场景名称"
                width="120"
                prop="themeName"
              >
              </el-table-column>
              <el-table-column label="开放状态" width="200">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.status"
                    active-value="1"
                    inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column
                prop="materials"
                label="材料"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <div v-for="(material, index) in formattedMaterials(scope.row)" :key="index" style="display: flex; align-items: center; margin-bottom: 5px;">
                    <img :src="material.pic" alt="material" style="width: 20px; height: 20px; margin-right: 10px;">
                    {{ material.name }}
                    观察次数：{{ material.Observation }}
                    意向次数：{{ material.Intention }}
                    总次数：{{ material.Observation + material.Intention}}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <cornerUser :visible.sync="cornerUserVisible" @cornerUserFile="cornerUserFile"></cornerUser>
    <CornerTheme :visible.sync="cornerThemeVisible" @themeFormSubmit="handleThemeFormSubmit"></CornerTheme>
    <getDevice :visible.sync="getDeviceVisible" @getDeviceFn="getDeviceFn"></getDevice>
    <AuxiliaryModule @getInformation="getInformation" :typeData="typeData"></AuxiliaryModule>
    <editCornerCateRule :visible.sync="ruleVisible" :cateId="cateData?cateData.id:0"></editCornerCateRule>
  </div>
</template>
<script>
import cornerUser from '@/components/dialog/cornerUser.vue'
import CornerTheme from '@/components/dialog/CornerTheme.vue'
import {qualityIndex} from '@/api/admin/acquisition'
import {cornerCateIndex} from '@/api/admin/corner'
import editCornerCateRule from "../components/editCornerCateRule";
import theme from "quill/core/theme";

export default {
  computed: {
    theme() {
      return theme
    },
    formattedMaterials() {
      return (row) => {
        if (!row.materials || !Array.isArray(row.materials)) {
          return [];
        }
        return row.materials.map(material => {
          let [id, name,pic, Observation,Intention] = material.split(':');
          Observation = parseInt(Observation) || 0;
          Intention = parseInt(Intention) || 0;
          return { id, name, pic,Observation:Observation,Intention:Intention,number: Intention + Observation };
        });
      };
    }
  },
  components: {
    cornerUser,
    CornerTheme,
    editCornerCateRule
  },
  props: ['editDetail', 'adminUser', 'applyBoxDetail', 'editId', 'cateData'],
  data() {
    return {
      typeData: 'corner_add',
      getDeviceVisible: false,
      cornerUserVisible: false,
      cornerThemeVisible: false,
      ruleVisible: false,
      editForm: {
        number: '', // 可参与的人数
        pic: '', // 现场图
        name: '', // 区角名称
        section_id: '', // 年段
        class_id: '', // 班级
        user_id: '', //负责人id
        facility_id: '', // 识别器
        time: '', // 达标时长
        base_score: '', // 基本分值
        cate_id: '',
        open_week: '',
        position_id: 1,
        themes: [], // 用于存储场景数据
      }, // 编辑界面数据
      applyBox: null,
      applyUserBox: null,
      dynamicTags: [],
      dynamicTagsId: [],
      dynamicTagsArray: {},
      is_base_score: true,
      getPower: {
        'section_id': {
          name: 'section_id', // key名称
          default: '', // 默认值
          propertyType: "Select", // 组件名称
          placeholder: '区角位置', // 默认值
          valueText: '', // 值
          leve: 2,
          api: this.api.user_sectionindex, // 下拉框的请求接口
          keyName: 'section_name',// 调用的字段
          child: [
            {
              name: 'class_id',
              default: '',
              propertyType: "",
              placeholder: '区角位置',
              valueText: '',
              api: this.api.user_classesindex,
              keyName: 'class_name',
            }
          ]
        }
      },
      study_ids: '',
      selectList: [],
      cateList: [],
      positionList: [
        {
          id: 1,
          name: '班级区角'
        },
        {
          id: 2,
          name: '公共室內'
        },
        {
          id: 3,
          name: '公共室外'
        }
      ],
      weekTime: [
        {
          id: 1,
          name: '周一早上'
        },
        {
          id: 2,
          name: '周一下午'
        },
        {
          id: 3,
          name: '周二早上'
        },
        {
          id: 4,
          name: '周二下午'
        },
        {
          id: 5,
          name: '周三早上'
        },
        {
          id: 6,
          name: '周三下午'
        },
        {
          id: 7,
          name: '周四早上'
        },
        {
          id: 8,
          name: '周四下午'
        },
        {
          id: 9,
          name: '周五早上'
        },
        {
          id: 10,
          name: '周五下午'
        },
        {
          id: 11,
          name: '周六早上'
        },
        {
          id: 12,
          name: '周六下午'
        },
        {
          id: 13,
          name: '周日早上'
        },
        {
          id: 14,
          name: '周日下午'
        }
      ]
    }
  },
  created() {
    this.getstudyPoint()
    this.getCateIndexFn()
  },
  methods: {
    getImgSrc(option) {
      this.editForm.pic = option
    },
    // 获取学习品质
    getstudyPoint() {
      qualityIndex({p: 1}).then(res => {
        this.selectList = res.list.data
      })
    },
    // 区角负责人
    cornerUserFn() {
      this.cornerUserVisible = !this.cornerUserVisible
    },
    cornerUserFile(option) {
      this.applyUserBox = option
      this.editForm.user_id = option.id
    },
    showDevice() {
      this.getDeviceVisible = !this.getDeviceVisible
    },
    showCornerTheme() {
      this.cornerThemeVisible = !this.cornerThemeVisible
    },
    handleThemeFormSubmit(themeData) {
      if (!Array.isArray(this.editForm.themes)) {
        this.editForm.themes = [];
      }
      this.editForm.themes.push(themeData);
    },
    studentFn(option) {
      this.dynamicTags = []
      this.dynamicTagsId = []
      for (let i in option) {
        this.dynamicTags.push(option[i].class_name) // class_name section_id
        this.dynamicTagsId.push(option[i].id)
        this.dynamicTagsArray = option
      }
      this.editForm.join_class = this.dynamicTagsId.join(',')
    },
    getChildValue(option) {
      this.editForm.pic = option
    },
    getDeviceFn(option) {
      this.applyBox = option;
      this.editForm.facility_id = option.id;
    },
    handleCloseDevice() {
      this.applyBox = null;
      this.editForm.facility_id = '';
    },
    // 更新值
    updateVal(option) {
      // console.log('变更数据收到的数据内容：', option)
      if (option.input) {
        this.editForm[option['input'].name] = option['input'].valueText
      } else if (option.select) {
        for (let i in option.select) {
          if (option.select[i].name) {
            this.editForm[option.select[i].name] = option.select[i].valueText
          } else {
            this.editForm[option.select[i - 1].name] = option.select[i].valueText ? option.select[i].valueText : option.select[i - 1].valueText
          }
        }
      }
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    getInformation(option) {
      for (let item of option) {
        if (item.type === 'img' && item.number === 1) {
          this.editForm.pic = item.value[0].url
        }
      }
    },
    getCateIndexFn() {
      cornerCateIndex({p: 0}).then(res => {
        this.cateList = res.list
      })
    },
    printPage() {
      window.print();
    }
  },

  mounted() {
  },
  watch: {
    // 识别号
    applyBoxDetail() {
      this.applyBox = this.getJson(this.applyBoxDetail)
    },
    adminUser() {
      this.applyUserBox = this.getJson(this.adminUser)
      this.editForm.user_id = this.adminUser.id
    },
    editDetail() {
      for (let i in this.editDetail) {
        if(i == 'open_week'){
          this.editForm[i] = this.editDetail[i].split(',').map(Number)
        } else if (i === 'themes') {
          try {
            this.editForm[i] = JSON.parse(this.editDetail[i]);
            console.log('解析后的 themes:', this.editForm[i]);
          } catch (error) {
            console.error('解析 JSON 字符串失败:', error);
            this.editForm[i] = [];
          }
        } else{
          this.editForm[i] = this.editDetail[i]
        }
      }
      let newGetPower = this.getJson(this.getPower)
      newGetPower['section_id'].valueText = this.editDetail['section_id']
      newGetPower['section_id'].child[0].valueText = this.editDetail['class_id']
      this.getPower = newGetPower
      this.study_ids = this.editDetail.study_ids.split(',').map(Number)
    },
    'editForm.number': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.pic': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.name': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.section_id': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.class_id': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.user_id': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.facility_id': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.time': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.base_score': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.description': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    study_ids() {
      this.$emit('getModleVal', {data: this.getJson(this.study_ids), type: 'study_ids'})
    },
    'editForm.cate_id': {
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.open_week':{
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.position_id':{
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    },
    'editForm.themes':{
      handler(val) {
        this.$emit('getModleVal', {data: this.getJson(this.editForm), type: 'form'})
      },
      deep: true
    }
  }
}
</script>
<style>
.edit-taps {
  font-size: 12px;
  padding-left: 5px;
  color: #999;
  font-style: normal;
}

.showCateFn:hover {
  color: #006dcd;
  text-decoration: underline;
}
.selectBox{
  width: 100%;
}
</style>
